package com.bwda.dsrs.filecenter.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwda.dsrs.base.centerbase.response.ResponseEntity;
import com.bwda.dsrs.filecenter.api.OrgServiceApi;
import com.bwda.dsrs.filecenter.domain.BusinessConstants;
import com.bwda.dsrs.filecenter.domain.condition.userlog.UserLogCondition;
import com.bwda.dsrs.filecenter.domain.condition.userlog.UserLogEsCondition;
import com.bwda.dsrs.filecenter.domain.vo.userlog.UserLogVo;
import com.bwda.dsrs.filecenter.service.LogQueryPageService;
import com.bwda.dsrs.filecenter.util.DateUtils;
import com.bwda.dsrs.filecenter.util.HttpClientUtil;
import com.bwda.dsrs.base.util.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * es查询用户日志
 *
 * @author liangjianyong
 * @date 2019/5/20
 */
@Service
public class UserLogEsServiceImpl implements LogQueryPageService {

    private final Logger logger= LoggerFactory.getLogger(UserLogEsServiceImpl.class);

    @Resource
    private OrgServiceApi orgServiceApi;

    /**
     *
     * @param condition
     * @return
     */
    @Override
    public UserLogVo queryList(UserLogCondition condition) {
        //获取es地址配置
        ResponseEntity esClientEntity = orgServiceApi.queryDatadictByCode(BusinessConstants.EsRestfulSearchParam.ES_CLINET_URL_DATACODE);
        String esClientUrl = (String)esClientEntity.getData();
        //获取es索引
        ResponseEntity esIndexEntity= orgServiceApi.queryDatadictByCode(BusinessConstants.EsRestfulSearchParam.LOG_INDEX_DATACODE);
        String esIndex=(String)esIndexEntity.getData();
        if(StringUtils.isBlank(esClientUrl)){
            logger.error("请在字典表中配置es客户端地址");
            return null;
        }
        if(StringUtils.isBlank(esIndex)){
            logger.error("请在字典表中配置es索引");
            return null;
        }
        Map<String, String> param = new HashMap<>(10);
        //EsClient需要的参数
        StringBuffer whereSql=new StringBuffer();
        if(StringUtils.isNotBlank(condition.getFileName())||condition.getStartTime()!=null||condition.getEndTime()!=null){
            whereSql.append("where 1=1").append(BusinessConstants.BLANK_ONE_STR);
            if(StringUtils.isNotBlank(condition.getFileName())){
                whereSql.append(BusinessConstants.EsRestfulSearchParam.AND_CHARATER)
                .append(BusinessConstants.BLANK_ONE_STR)
                .append(BusinessConstants.EsRestfulSearchParam.FILE_NAME_FILED)
                    .append(" like \"%").append(condition.getFileName()).append("\"%");
            }
            if(condition.getStartTime()!=null){
                whereSql .append(BusinessConstants.BLANK_ONE_STR)
                        .append(BusinessConstants.EsRestfulSearchParam.AND_CHARATER)
                        .append(BusinessConstants.BLANK_ONE_STR)
                        .append(BusinessConstants.EsRestfulSearchParam.DATE_STAMP)
                        .append(" >"+condition.getStartTime().getTime());
            }
            if(condition.getEndTime()!=null){
                whereSql .append(BusinessConstants.BLANK_ONE_STR)
                        .append(BusinessConstants.EsRestfulSearchParam.AND_CHARATER)
                        .append(BusinessConstants.BLANK_ONE_STR)
                        .append(BusinessConstants.EsRestfulSearchParam.DATE_STAMP)
                        .append(" <"+condition.getEndTime().getTime());
            }
        }
        StringBuffer pageSql=new StringBuffer();
        pageSql.append("select * from ")
            .append(esIndex+ DateUtils.getYearMonth())
            .append(BusinessConstants.BLANK_ONE_STR)
            .append(whereSql.toString())
            .append(BusinessConstants.BLANK_ONE_STR)
            .append(BusinessConstants.EsRestfulSearchParam.ORDER_CHARATER)
            .append(BusinessConstants.BLANK_ONE_STR)
            .append(BusinessConstants.EsRestfulSearchParam.LIMIT_CHARATER)
            .append(BusinessConstants.BLANK_ONE_STR)
            .append(condition.getPageNum()*condition.getPageSize())
            .append(BusinessConstants.EsRestfulSearchParam.COMMA_CHARATER)
            .append((condition.getPageNum()+1)*condition.getPageSize());
        StringBuffer totalsql=new StringBuffer();
        totalsql.append("select count(*) from ")
            .append(esIndex+ DateUtils.getYearMonth()).append(BusinessConstants.BLANK_ONE_STR).append(whereSql.toString())
                .append(BusinessConstants.BLANK_ONE_STR)
                .append(BusinessConstants.EsRestfulSearchParam.ORDER_CHARATER);
        param.put("pagesql",pageSql.toString());
        param.put("totalsql",totalsql.toString());
        String resultString = HttpClientUtil.doPost(esClientUrl.concat(BusinessConstants.EsRestfulSearchParam.ESCLIENT_PATH), param);
        UserLogVo pageVo= JSONObject.parseObject(resultString, UserLogVo.class);
        return pageVo;

    }

    /**
     * 条件参数转换
     * @return
     */
    private UserLogEsCondition getConsumerLogEsCondition(UserLogCondition condition){
        UserLogEsCondition newCondition=new UserLogEsCondition();
        if(condition.getStartTime()!=null){
            newCondition.setStartCreateDate(DateUtil.formatDate(condition.getStartTime(),BusinessConstants.EsRestfulSearchParam.DATE_FORMAT));
        }
        if(condition.getEndTime()!=null){
            newCondition.setEndCreateDate(DateUtil.formatDate(condition.getEndTime(),BusinessConstants.EsRestfulSearchParam.DATE_FORMAT));
        }
        return newCondition;
    }

    public static void main(String[] arg){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            Date date1 = simpleDateFormat.parse("2019-05-15 00:00");
            System.out.println("开始时间"+date1);
            Date date2 = simpleDateFormat.parse("2019-05-20 00:00");
            System.out.println("结束时间"+date2);
        } catch (ParseException e) {
            e.printStackTrace();
        }


    }


}
